<template>
    <div class="invoice-receipt-add">
        <el-card shadow="never" class="main-card">
            <template #header>
                <div class="card-header">
                    <span class="header-title">到票添加</span>
                    <div class="header-actions">
                        <el-button type="primary" :loading="submitting" @click="onSubmit" class="submit-btn">
                            保存
                        </el-button>
                        <el-button @click="onReset">重置</el-button>
                        <el-button text type="info" @click="goBack">返回</el-button>
                    </div>
                </div>
            </template>

            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" status-icon class="receipt-form">
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="发票ID" prop="invoiceId" class="form-item">
                            <el-select v-model="form.invoiceId" placeholder="请选择发票" filterable
                                :loading="invoicesLoading" style="width: 100%">
                                <el-option v-for="opt in invoiceOptions" :key="opt.invoiceId" :label="opt.invoiceNo"
                                    :value="opt.invoiceId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="收款日期" prop="receiptDate" class="form-item">
                            <el-date-picker v-model="form.receiptDate" type="date" placeholder="选择日期"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="收款金额" prop="receiptAmount" class="form-item">
                            <el-input-number v-model="form.receiptAmount" :min="0" :step="0.01" :precision="2"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="收款状态" prop="receiptStatus" class="form-item">
                            <el-select v-model="form.receiptStatus" placeholder="请选择状态" style="width: 100%">
                                <el-option label="未收款" value="0" />
                                <el-option label="部分收款" value="1" />
                                <el-option label="已收款" value="2" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="付款方式" prop="paymentMethod" class="form-item">
                            <el-input v-model="form.paymentMethod" placeholder="请输入付款方式" clearable
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="交易单号" prop="transactionNo" class="form-item">
                            <el-input v-model="form.transactionNo" placeholder="请输入交易单号" clearable
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remarks" class="form-item">
                            <el-input v-model="form.remarks" placeholder="备注信息(可选)" clearable type="textarea"
                                :rows="3" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <!-- 信息展示区域 -->
            <div class="receipt-info" v-if="selectedInvoiceInfo">
                <el-divider>发票信息</el-divider>
                <div class="info-grid">
                    <div class="info-item">
                        <span class="info-label">发票号码：</span>
                        <span class="info-value">{{ selectedInvoiceInfo.invoiceNo }}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">客户名称：</span>
                        <span class="info-value">{{ selectedInvoiceInfo.customerName }}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">发票金额：</span>
                        <span class="info-value amount">{{ formatMoney(selectedInvoiceInfo.invoiceAmount) }}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">已收金额：</span>
                        <span class="info-value received">{{ formatMoney(selectedInvoiceInfo.receivedAmount) }}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">待收金额：</span>
                        <span class="info-value pending">{{ formatMoney(selectedInvoiceInfo.pendingAmount) }}</span>
                    </div>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { APIs } from '@/Http/http'
import { useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter'

// 定义发票收款表单类型
interface InvoiceReceiptForm {
    invoiceId: number | null
    receiptDate: string | Date
    receiptAmount: number
    receiptStatus: number
    paymentMethod: string
    transactionNo: string
    remarks: string
    createName: string
}

// 定义发票信息类型
interface InvoiceInfo {
    invoiceId: number
    invoiceNo: string
    customerName: string
    invoiceAmount: number
    receivedAmount: number
    pendingAmount: number
}

const router = useRouter()
const submitting = ref(false)
const formRef = ref<FormInstance>()
const store = useCounterStore()
const invoicesLoading = ref(false)

const selectedInvoiceInfo = ref<InvoiceInfo | null>(null)

// 表单数据
const form = reactive<InvoiceReceiptForm>({
    invoiceId: null,
    receiptDate: new Date(),
    receiptAmount: 0,
    receiptStatus: 0,
    paymentMethod: '',
    transactionNo: '',
    remarks: '',
    createName: store.Users.userNickname || ''
})

// 表单验证规则
const rules = reactive<FormRules<InvoiceReceiptForm>>({
    invoiceId: [
        { required: true, message: '请选择发票', trigger: 'blur' }
    ],
    receiptDate: [
        { required: true, message: '请选择收款日期', trigger: 'change' }
    ],
    receiptAmount: [
        { required: true, message: '请输入收款金额', trigger: 'blur' },
        { type: 'number', min: 0.01, message: '收款金额必须大于0', trigger: 'blur' }
    ],
    receiptStatus: [
        { required: true, message: '请选择收款状态', trigger: 'blur' }
    ],
    paymentMethod: [
        { required: true, message: '请输入付款方式', trigger: 'blur' }
    ],
    transactionNo: [
        { required: true, message: '请输入交易单号', trigger: 'blur' }
    ]
})
const invoiceOptions = ref([{
    "invoiceId": 0,
    "invoiceNo": "",
    "orderId": 1,
    "orderNo": null,
    "customerId": 1,
    "customerName": "",
    "invoiceAmount": 0,
    "invoiceDate": "2025-09-22T06:47:31.561",
    "invoiceType": "string",
    "invoiceStatus": 0,
    "invoiceStatusName": "待开具",
    "taxRate": 0,
    "taxAmount": 0,
    "subtotalAmount": 0,
    "remarks": "string",
    "createName": "string",
    "createTime": "2025-09-22T14:47:59.9092",
    "updateTime": "2025-09-22T14:47:59.909202",
    "updateName": null,
    "details": null
}])
// 加载发票列表 - 按照中介者模式返回APIRequest类型
function loadInvoiceOptions() {
    invoicesLoading.value = true
    console.log('开始加载发票列表...');
    APIs.get('/api/SalesInvoice/GetAllSalesInvoiceList').then((res: any) => {
        console.log('发票列表接口返回数据:', res);
        invoiceOptions.value = res.data.data;
    }).catch((error: any) => {
        ElMessage.error('发票列表加载失败')
        console.error('获取发票列表出错:', error);
    }).finally(() => {
        invoicesLoading.value = false
        console.log('发票列表加载流程结束');
    })
}

// 处理发票选择变化
// function onInvoiceChange(invoiceId: number | null | undefined) {
//     console.log('发票选择变化事件触发，接收到的invoiceId:', invoiceId);

//     // 验证invoiceId是否有效
//     if (!invoiceId || isNaN(Number(invoiceId)) || Number(invoiceId) <= 0) {
//         selectedInvoiceInfo.value = null
//         form.invoiceId = null
//         console.log('无效的发票ID:', invoiceId, '类型:', typeof invoiceId);
//         return
//     }

//     // 确保invoiceId是数字类型
//     const numericInvoiceId = Number(invoiceId);

//     // 同步设置form.invoiceId
//     form.invoiceId = numericInvoiceId
//     console.log('设置form.invoiceId为:', form.invoiceId);

//     // 调用API获取发票详情
//     APIs.get(`/api/SalesInvoice/GetSalesInvoiceDetail?invoiceId=${numericInvoiceId}`).then((res: any) => {
//         console.log('获取发票详情返回:', res);

//         if (res?.code === 100 && res?.data) {
//             const invoiceData = res.data
//             console.log('发票详情数据:', invoiceData);

//             // 设置选中的发票信息
//             selectedInvoiceInfo.value = {
//                 invoiceId: numericInvoiceId,
//                 invoiceNo: invoiceData.invoiceNo || '',
//                 customerName: invoiceData.customerName || '',
//                 invoiceAmount: Number(invoiceData.invoiceAmount || 0),
//                 receivedAmount: Number(invoiceData.receivedAmount || 0),
//                 pendingAmount: Number(invoiceData.pendingAmount || 0)
//             }
//             console.log('设置selectedInvoiceInfo:', selectedInvoiceInfo.value);

//             // 自动设置收款金额和状态
//             if (selectedInvoiceInfo.value.pendingAmount > 0) {
//                 form.receiptAmount = selectedInvoiceInfo.value.pendingAmount
//                 form.receiptStatus = 2 // 已收款
//                 console.log('自动设置为全额收款:', form.receiptAmount);
//             } else if (selectedInvoiceInfo.value.receivedAmount > 0) {
//                 form.receiptStatus = 1 // 部分收款
//                 console.log('自动设置为部分收款状态');
//             } else {
//                 form.receiptStatus = 0 // 未收款
//                 console.log('自动设置为未收款状态');
//             }

//             console.log('自动设置收款金额:', form.receiptAmount);
//         } else {
//             // 降级方案：从现有选项中查找
//             console.log('发票详情API返回格式不正确，尝试降级查找');
//             const invoiceOpt = invoiceOptions.value.find(opt => opt.value === numericInvoiceId)
//             if (invoiceOpt) {
//                 selectedInvoiceInfo.value = {
//                     invoiceId: numericInvoiceId,
//                     invoiceNo: invoiceOpt.label,
//                     customerName: invoiceOpt.customerName || '',
//                     invoiceAmount: Number(invoiceOpt.invoiceAmount || 0),
//                     receivedAmount: 0,
//                     pendingAmount: Number(invoiceOpt.invoiceAmount || 0)
//                 }
//                 console.log('降级查找成功，设置selectedInvoiceInfo:', selectedInvoiceInfo.value);

//                 // 降级方案也自动设置收款金额
//                 form.receiptAmount = selectedInvoiceInfo.value.pendingAmount
//                 form.receiptStatus = 2 // 已收款
//             } else {
//                 selectedInvoiceInfo.value = null
//                 form.invoiceId = null
//                 ElMessage.warning('未找到发票详情')
//                 console.log('降级查找失败，未找到匹配的发票选项');
//             }
//         }
//     }).catch((error: any) => {
//         ElMessage.error('获取发票详情失败')
//         console.error('获取发票详情出错:', error);

//         // 降级方案：从现有选项中查找
//         const invoiceOpt = invoiceOptions.value.find(opt => opt.value === invoiceId)
//         if (invoiceOpt) {
//             selectedInvoiceInfo.value = {
//                 invoiceId: Number(invoiceId),
//                 invoiceNo: invoiceOpt.label,
//                 customerName: invoiceOpt.customerName || '',
//                 invoiceAmount: Number(invoiceOpt.invoiceAmount || 0),
//                 receivedAmount: 0,
//                 pendingAmount: Number(invoiceOpt.invoiceAmount || 0)
//             }
//         } else {
//             console.log('降级查找失败，未找到匹配的发票选项');
//         }
//     })
// }

// 格式化金额
function formatMoney(v: number | string) {
    const n = Number(v || 0)
    return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 重置表单
function onReset() {
    ElMessageBox.confirm('确定要重置表单吗？', '提示', {
        type: 'warning'
    }).then(() => {
        form.invoiceId = null
        form.receiptDate = new Date()
        form.receiptAmount = 0
        form.receiptStatus = 0
        form.paymentMethod = ''
        form.transactionNo = ''
        form.remarks = ''
        form.createName = store.Users.userNickname || ''
        selectedInvoiceInfo.value = null
    }).catch(() => { })
}

// 返回上一页
function goBack() {
    router.back()
}

// 提交表单 - 按照中介者模式返回APIRequest类型
function onSubmit() {
    if (!formRef.value) return
    formRef.value.validate((valid): any => {
        if (!valid) return false

        submitting.value = true
        // 组织与后端一致的数据结构
        const payload = {
            invoiceId: Number(form.invoiceId || 0),
            receiptDate: form.receiptDate ? new Date(form.receiptDate).toISOString() : new Date().toISOString(),
            receiptAmount: Number(form.receiptAmount) || 0,
            receiptStatus: Number(form.receiptStatus) || 0,
            paymentMethod: form.paymentMethod || '',
            transactionNo: form.transactionNo || '',
            remarks: form.remarks || '',
            createName: store.Users.userNickname || form.createName || ''
        }

        // 调用新增收款接口 - 按照中介者模式返回APIRequest类型
        APIs.post('/api/SalesInvoice/AddInvoiceReceipt', payload).then((res: any) => {
            if (res && (res.status === 200 || res.status === 201)) {
                ElMessage.success('添加成功')
                // 重置表单，可以选择返回或继续添加
                onReset()
            } else {
                ElMessage.error('保存失败')
            }
        }).catch((error: any) => {
            ElMessage.error(error?.response?.data?.message || '请求失败')
        }).finally(() => {
            submitting.value = false
        })

        return false
    })
}

// 组件挂载时加载发票列表
onMounted(() => {
    loadInvoiceOptions()
})
</script>

<style scoped>
.invoice-receipt-add {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;
}

.main-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
    overflow: hidden;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px 16px;
    border-bottom: 1px solid #ebeef5;
}

.header-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
}

.header-actions {
    display: flex;
    gap: 12px;
}

.submit-btn {
    font-weight: 500;
}

.receipt-form {
    padding: 24px;
}

.form-item {
    margin-bottom: 20px;
}

.receipt-info {
    background-color: #fafafa;
    padding: 24px;
    border-top: 1px solid #ebeef5;
}

.info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 16px;
    margin-top: 16px;
}

.info-item {
    display: flex;
    align-items: center;
    padding: 12px;
    background: white;
    border-radius: 6px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.info-label {
    color: #606266;
    font-size: 14px;
    min-width: 100px;
}

.info-value {
    color: #303133;
    font-size: 14px;
    font-weight: 500;
}

.info-value.amount {
    color: #e6a23c;
}

.info-value.received {
    color: #67c23a;
}

.info-value.pending {
    color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .invoice-receipt-add {
        padding: 10px;
    }

    .card-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
    }

    .header-actions {
        width: 100%;
        justify-content: flex-end;
    }

    .receipt-form {
        padding: 16px;
    }

    .info-grid {
        grid-template-columns: 1fr;
    }
}
</style>